<template>
  <div>
    <el-dialog
      top="15vh"
      width="800px"
      :title="title"
      :show-close="true"
      :lock-scroll="true"
      :append-to-body="false"
      :destroy-on-close="true"
      :visible.sync="data_visible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="dialogDestroy"
    >
      <div class="main">
        <el-form
          ref="form"
          :model="data_form.data"
          :rules="data_form.rules"
          label-width="80px"
        >
          <el-form-item label="联系人：" prop="name" label-width="100px">
            <el-input
              v-model="data_form.data.name"
              type="text"
              maxlength="10"
            />
          </el-form-item>
          <el-form-item label="联系电话：" prop="phone" label-width="100px">
            <el-input
              v-model="data_form.data.phone"
              type="tel"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="省份：" prop="province" label-width="100px">
            <el-select
              v-model="data_form.data.province"
              placeholder="请选择"
              :loading="data_form.ext_data.province_select_loading"
              @focus="provinceFocusHandler"
              @change="provinceChangeHandler"
            >
              <el-option
                v-for="(val, key) in data_form.ext_data.province_list"
                :key="key"
                :label="val"
                :value="[key, val]"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="地市：" prop="city" label-width="100px">
            <el-select
              v-model="data_form.data.city"
              placeholder="请选择"
              @change="cityChangeHandler"
            >
              <el-option
                v-for="(val, key) in data_form.ext_data.city_list"
                :key="key"
                :label="val"
                :value="[key, val]"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="区县：" prop="county" label-width="100px">
            <el-select v-model="data_form.data.county" placeholder="请选择">
              <el-option
                v-for="(val, key) in data_form.ext_data.county_list"
                :key="key"
                :label="val"
                :value="[key, val]"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址：" prop="detail" label-width="100px">
            <el-input
              v-model="data_form.data.detail"
              type="textarea"
              :style="{ lineHeight: 'initial' }"
              autosize
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">
          取 消
        </el-button>
        <el-button type="primary" :disabled="false" @click="dialogConfirm">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ApiMMallWeb } from '@services/api';

export default {
  name: 'AddressAddDialogComponent',
  props: {
    title: {
      type: String,
      default: '新增收货地址'
    },
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default() {}
    },
    fetcher: {
      type: Function,
      default() {}
    }
  },
  data() {
    return {
      itemAddress: {},
      data_form: {
        data: {
          name: '',
          city: '',
          cityCode: '',
          county: '',
          countyCode: '',
          province: '',
          provinceCode: '',
          phone: '',
          detail: '',
          id: ''
        },
        ext_data: {
          city_list: {},
          county_list: {},
          province_list: {},
          province_select_loading: false
        },
        rules: {
          name: [
            { required: true, message: '请输入联系人', trigger: 'blur' },
            {
              min: 2,
              max: 10,
              message: '长度在 2 到 10 个字符',
              trigger: 'blur'
            }
          ],
          phone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { min: 11, max: 20, message: '请输入正确联系方式', trigger: 'blur' }
            // { pattern: /^(\d|\-)*$/, message: '只支持输入数字和-', trigger: 'blur' },
            // {
            //   pattern: /^(1[3-9][0-9]{9}|0[1-9][0-9]{1,2}-[1-9][0-9]{6,7})$/,
            //   message: '仅支持11位手机号码输入和座机(区号-号码)输入',
            //   trigger: 'blur'
            // }
          ],
          city: [{ required: true, message: '请选择地市', trigger: 'change' }],
          county: [
            { required: true, message: '请选择区县', trigger: 'change' }
          ],
          province: [
            { required: true, message: '请选择省份', trigger: 'change' }
          ],
          detail: [
            { required: true, message: '请输入详细地址', trigger: 'blur' },
            {
              min: 5,
              max: 50,
              message: '长度在 5 到 100 个字符',
              trigger: 'blur'
            }
          ]
        }
      },
      data_visible: true
    };
  },
  computed: {
    apiMMallWeb() {
      return new ApiMMallWeb(this.fetcher);
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        this.data_visible = val;
      }
    }
  },
  created() {
    this.assignment();
  },
  methods: {
    async assignment() {
      // console.log(this.data, '208-------');
      this.data_form.data.name = this.data.userName;
      this.data_form.data.phone = this.data.userPhone;
      this.data_form.data.province = this.data.province;
      this.data_form.data.provinceCode = this.data.provinceCode;
      this.data_form.data.city = this.data.city;
      this.data_form.data.cityCode = this.data.cityCode;
      this.data_form.data.countyCode = this.data.areaCode;
      this.data_form.data.county = this.data.area;
      this.data_form.data.detail = this.data.detailedAddress;
      this.data_form.data.id = this.data.id;
      if (this.data.id) {
        this.data_form.ext_data.city_list = await this.pullAddressData({
          provinceCode: this.data_form.data.provinceCode
        });
        this.data_form.ext_data.county_list = await this.pullAddressData({
          cityCode: this.data_form.data.cityCode
        });
      }
    },
    dialogDestroy() {
      this.$emit('destroy', true);
      this.$emit('update:visible', false);
    },
    dialogClose() {
      this.data_visible = false;
    },
    dialogConfirm() {
      // eslint-disable-next-line consistent-return
      this.$refs.form.validate(async success => {
        if (success) {
          const { data } = this.data_form;
          data.city = data.city || [];
          data.county = data.county || [];
          data.province = data.province || [];
          if (this.dialogConfirmIng) {
            return false;
          }
          this.dialogConfirmIng = true;
          let result = null;
          if (data.id) {
            result = await this.pushAddressItemData({
              newMallAddressReqDto: {
                userName: data.name,
                userPhone: data.phone,
                area:
                  typeof data.county === 'string'
                    ? data.county
                    : data.county[1],
                areaCode:
                  typeof data.county === 'string'
                    ? data.county
                    : data.county[0],
                city: typeof data.city === 'string' ? data.city : data.city[1],
                cityCode:
                  typeof data.city === 'string' ? data.city : data.city[0],
                province:
                  typeof data.province === 'string'
                    ? data.province
                    : data.province[1],
                provinceCode:
                  typeof data.province === 'string'
                    ? data.province
                    : data.province[0],
                detailedAddress: data.detail,
                id: data.id
              }
            });
          } else {
            result = await this.pushAddressItemData({
              newMallAddressReqDto: {
                userName: data.name,
                userPhone: data.phone,
                area: data.county[1],
                areaCode: data.county[0],
                city: data.city[1],
                cityCode: data.city[0],
                province: data.province[1],
                provinceCode: data.province[0],
                detailedAddress: data.detail
                // id: data.id
              }
            });
          }

          if (result) {
            this.data_visible = false;
            this.$emit('confirm', result);
          }
          this.dialogConfirmIng = false;
        }
      });
    },
    async cityChangeHandler([cityCode]) {
      this.data_form.data.county = '';
      this.data_form.ext_data.county_list = await this.pullAddressData({
        cityCode
      });
    },
    async provinceFocusHandler() {
      if (Object.keys(this.data_form.ext_data.province_list).length === 0) {
        this.data_form.ext_data.province_select_loading = true;
        this.data_form.ext_data.province_list = await this.pullAddressData();
      }
      this.data_form.ext_data.province_select_loading = false;
    },
    async provinceChangeHandler([provinceCode]) {
      this.data_form.data.city = '';
      this.data_form.data.county = '';
      this.data_form.ext_data.city_list = await this.pullAddressData({
        provinceCode
      });
    },
    pullAddressData(params = {}) {
      return this.apiMMallWeb.ListAreaV1ApiPOST(params);
    },
    pushAddressItemData(params = {}) {
      return this.apiMMallWeb.SaveOrderAddressOrderAddressV1ApiPOST(params);
    }
  }
};
</script>

<style lang="less" scoped></style>
